package cc.rengu.igas.share.core.service.asyncall;

import cc.rengu.igas.acct.facade.response.VirtAcctPreAuthCompResponse;
import cc.rengu.igas.acct.facade.result.Result;
import cc.rengu.oltp.service.base.DubboAsynBaseService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.MchntOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.PayOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.MchntOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.PayOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.enums.BizStatusEnum;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.utility.annotation.BIZ_PROCESS;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 虚拟账户单笔预授权完成异步处理
 */
public class AsynVirtAcctSinglePreAuthCompService extends DubboAsynBaseService {
    @BIZ_PROCESS
    public void virtAcctMultiMchntAdjust() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysNo = null;
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        PayOrderInfoMapper payOrderInfoMapper = new PayOrderInfoMapperImpl();

        OrderService orderService = new OrderServiceImpl();

        /*判断记账结果，更新支付订单状态*/
        if (!xmlTreeUtil.isExist(TreeNodeConstant.DUBBO_RESPONSE)) {
            rglog.error("dubbo调用失败");
            return;
        }
        rglog.debug("dubbo调用正常返回");
        Result<JSONObject> responseResult = (Result<JSONObject>) xmlTreeUtil.getXmlTreeObjectValue(TreeNodeConstant.DUBBO_RESPONSE, Result.class);
        if (!responseResult.isSuccess()) {
            rglog.warn("dubbo调用失败");
            return;
        }

        VirtAcctPreAuthCompResponse response = JSON.toJavaObject(responseResult.getResult(), VirtAcctPreAuthCompResponse.class);
        /*避免退款成功发起记账跟查询交易发起记账系统流水号不一致的问题,取调用虚拟账户记账的traceNo*/
        if (response.getHeader() != null && response.getHeader().getTraceNo() != null) {
            sysNo = response.getHeader().getTraceNo().substring(0, 32);
        } else {
            rglog.error("dubbo调用虚拟账户记账失败");
            return;
        }
        /*获取支付订单列表*/
        List<PayOrderInfo> payOrderInfoList = payOrderInfoMapper.selectPayOrderInfoBySysSeqNum(instId, sysNo);
        if (payOrderInfoList == null || payOrderInfoList.size() == 0) {
            rglog.error("根据机构号<{}>、系统流水号<{}>获取支付订单列表失败", instId, sysNo);
            return;
        }
        List<PayOrderInfo> payOrderInfoListAcct = payOrderInfoList.stream().filter(item -> item.getMsgDstId().equals(ChannelEnum.ACCT.getChannelType())).collect(Collectors.toList());
        rglog.debug("获取到虚拟账户的支付订单数据条数:<{}>", payOrderInfoListAcct.size());
        if (payOrderInfoListAcct.size() != 2) {
            rglog.error("查询虚拟支付订单流水记录异常");
            return;
        }
        //预授权订单
        PayOrderInfo preAuthPayOrderInfo = payOrderInfoListAcct.get(0);
        //预授权完成订单
        PayOrderInfo preAuthFinishPayOrderInfo = payOrderInfoListAcct.get(1);
        if (!OltpRpcdEnum.TRANS_SUCCESS.getRespCode().equals(response.getRespCode()) || !"00".equals(response.getTransStatus())) {
            rglog.error("业务处理失败respCode<{}>,respDesc<{}>", response.getRespCode(), response.getRespDesc());
            /*更新支付订单表失败*/
            preAuthFinishPayOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            preAuthFinishPayOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
            preAuthFinishPayOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            if (!orderService.updateOrderInfo(null, null, preAuthFinishPayOrderInfo)) {
                rglog.error("更新预授权完成订单表状态失败");
            }
            return;
        }
        /*查询商户的订单*/
        MchntOrderInfoMapper opmsMchntOrderInfoMapper = new MchntOrderInfoMapperImpl();
        List<MchntOrderInfo> mchntOrderInfoList = opmsMchntOrderInfoMapper.selectMchntOrderInfoBySysSeqNum(instId, sysNo);
        if (mchntOrderInfoList == null || mchntOrderInfoList.size() == 0) {
            rglog.info("商户订单信息表中无该笔订单,instId:<{}>,sysSeqNum:<{}>.", instId, sysNo);
            return;
        } else if (mchntOrderInfoList.size() > 1) {
            rglog.info("单商户预授权查询商户订单信息表中大于1笔订单,instId:<{}>,sysSeqNum:<{}>.", instId, sysNo);
            return;
        }
        for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
            /*更新虚拟账户余额*/
            mchntOrderInfo.setVirtualAcctBalance(response.getAfterBalance());
            mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        }

        /*更新支付订单表成功*/
        preAuthFinishPayOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
        preAuthFinishPayOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
        preAuthFinishPayOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        if (!orderService.updateOrderInfo(null, null, preAuthFinishPayOrderInfo)) {
            rglog.error("更新预授权完成订单表状态失败");
        }

        /*更新预授权订单完成*/
        preAuthPayOrderInfo.setBizStatus(BizStatusEnum.AUTH_COMPLETE.getStatus());
        preAuthPayOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        if (!orderService.updateOrderInfo(null, mchntOrderInfoList, preAuthPayOrderInfo)) {
            rglog.error("更新预授权订单表状态失败");
        }
    }
}
